import {Component, OnInit} from '@angular/core';
import {AppService} from '../../../app.service';
import {FileManagementService} from '../file-management.service';
import {CommonTool} from '../../../common/common.tool';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {TableFindModel} from '../../../common/table-find/table-find.model';
import {SystemDto} from '../../../base/base.model';
import {environment} from '../../../../environments/environment';

@Component({
  selector: 'app-safety-chain-management',
  templateUrl: './safety-chain.component.html',
  styleUrls: ['./safety-chain.component.scss']
})
export class SafetyChainComponent implements OnInit {

  public commonTool = CommonTool;
  public tableFindModel: TableFindModel;
  public tableFindModel1: TableFindModel;
  public isEditVisible = false;
  public selectFolder = {isVisible: false, isCopy: true, okText: '确定'};
  public formInfo: {
    id: string
    name: string
    url: string
    folderId: string
    folderName: string
  };
  public parentId;
  public folderList: Array<any>;
  public imgConfig = {};
  public system: SystemDto;

  constructor(public fileManagementService: FileManagementService,
              private message: NzMessageService,
              public appService: AppService,
              private modalService: NzModalService) {
    // 获取系统信息
    this.system = new SystemDto(JSON.parse(sessionStorage.getItem(environment.systemKey)));
    for (const systemInfo of this.system.systemInfos) {
      this.imgConfig[systemInfo.code] = systemInfo.value;
    }
    const COMMON_TYPE = TableFindModel.COMMON_TYPE;
    this.tableFindModel = new TableFindModel();
    this.tableFindModel1 = new TableFindModel();
    const myThis = this;
    const config = {
      tables: [
        {name: '名称', field: 'name', type: COMMON_TYPE.table.TEXT, isSort: true},
        {name: '文件夹名称', field: 'folderName', type: COMMON_TYPE.table.TEXT},
        {name: '地址', field: 'url', type: COMMON_TYPE.table.TEXT, isSort: true},
        {
          name: '操作', field: '', type: COMMON_TYPE.table.OPERATE,
          operates: [
            {
              name: '编辑', field: 'edit', confirmFun(dataModel, that) {
                myThis.isEditVisible = true;
                myThis.formInfo = {
                  id: dataModel.data.id,
                  name: dataModel.data.name,
                  url: dataModel.data.url,
                  folderId: dataModel.data.folderId,
                  folderName: dataModel.data.folderName
                };
                myThis.parentId = 'root';
                myThis.init1();
              }
            },
            {
              name: '删除', field: 'delete', confirmFun(dataModel, that) {
                myThis.delete(dataModel.data.id);
              }
            }
          ]
        }
      ],
      finds: [
        {name: '名称', field: 'name', type: COMMON_TYPE.find.INPUT},
        {name: '地址', field: 'url', type: COMMON_TYPE.find.INPUT}
      ],
      buttons: [
        {
          name: '新增',
          type: COMMON_TYPE.button.MIDDLING,
          icon: 'plus-circle',
          confirmFun(formInfo, that) {
            myThis.formInfo = {
              id: '',
              name: '',
              url: '',
              folderId: '',
              folderName: ''
            };
            myThis.isEditVisible = true;
            myThis.parentId = 'root';
            myThis.init1();
          }
        },
        {
          name: '搜索',
          type: COMMON_TYPE.button.SEARCH,
          icon: 'search'
        }
      ],
      initDataFun(formInfo, sortPage, callback, that) {// 数据处理回调 config：配置，dataModels：数据，that：当前对象
        myThis.formInfo = {
          id: '',
          name: '',
          url: '',
          folderId: '',
          folderName: ''
        };
        const req = {
          size: sortPage.size,
          sortField: sortPage.sortField,
          sortRule: sortPage.sortRule,
          likeFields: ['name', 'url'],
          name: formInfo['name'],
          url: formInfo['url']
        };
        myThis.fileManagementService.getUserSafetyChainPage(sortPage.current, req).subscribe(res => {
          myThis.fileManagementService.getUserFolderList({}).subscribe(folders => {
            myThis.appService.setLoading(false);
            myThis.folderList = folders;
            const array = [];
            for (const resData of res['resData']) {
              if (resData.folderId === 'root') {
                resData['folderName'] = 'root';
                resData['parentId'] = 'root';
              } else {
                for (const folder of  myThis.folderList) {
                  if (folder.id === resData.folderId) {
                    resData['folderName'] = folder.name;
                    resData['parentId'] = folder.parentId;
                  }
                }
              }
              array.push({data: resData});
            }
            callback(array, {total: res.total});
          });
        });
      },
      frontPaging: false,
      frontSort: false
    };
    this.tableFindModel.initConfig(config);
  }

  ngOnInit() {

  }

  /**
   * 初始化选择数据
   */
  public init1() {
    const COMMON_TYPE = TableFindModel.COMMON_TYPE;
    const myThis = this;
    const config1 = {
      finds: [
        {name: '文件夹名', field: 'name', type: COMMON_TYPE.find.INPUT}
      ],
      tables: [
        {
          name: '', field: 'imageUrl', type: COMMON_TYPE.table.IMAGE,
          imageStyle: {cursor: 'pointer'},
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              myThis.parentId = dataModel.data.id;
              that.getData(null, null);
            }
          }
        },
        {
          name: '文件夹名',
          field: 'name',
          type: COMMON_TYPE.table.TITLE,
          isSort: true,
          titleStyle: {cursor: 'pointer'},
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              myThis.parentId = dataModel.data.id;
              that.getData(null, null);
            }
          }
        }, {
          name: '', field: 'createTime', type: COMMON_TYPE.table.DESCRIPTION,
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              myThis.parentId = dataModel.data.id;
              that.getData(null, null);
            }
          }
        }
      ],
      buttons: [
        {name: '搜索', type: COMMON_TYPE.button.SEARCH}
      ],
      breadcrumb: {
        breadcrumbFun: (label) => {
          if (label['data'] != null) {
            myThis.parentId = label['data'].id;
          } else {
            myThis.parentId = 'root';
          }
          myThis.tableFindModel1.getData(null, null);
        },
        labels: [] // 面包屑
      },
      initDataFun(formInfo, sortPage, callback, that) {// 数据处理回调 config：配置，dataModels：数据，that：当前对象
        const req = {
          sortField: sortPage.sortField,
          sortRule: sortPage.sortRule,
          likeFields: ['name'],
          parentId: myThis.parentId,
          name: formInfo['name']
        };
        if (formInfo['name']) {
          req['parentId'] = null;
        } else if (!myThis.parentId) {
          req['parentId'] = 'root';
        }
        myThis.fileManagementService.getUserFolderList(req).subscribe(res => {
          const array = [];
          for (const arr of res) {
            arr['imageUrl'] = myThis.imgConfig['disk_icon_folder'];
            array.push({
              data: arr,
              isFile: false
            });
          }
          myThis.fileManagementService.getUserParentFolder(req['parentId']).subscribe(folders => {
            const labels = [{name: '全部', data: null}];
            for (const folder of folders.reverse()) {
              folder['imageUrl'] = myThis.imgConfig['disk_icon_folder'];
              labels.push({name: folder.name, data: folder});
            }
            myThis.tableFindModel1.config.breadcrumb.labels = labels;
          });
          callback(array, {size: array.length});
        });
      },
      openPaging: false,
      frontSort: false,
      openButton: false
    };
    this.tableFindModel1.initConfig(config1);
  }

  /**
   * 保存文件
   */
  public saveFolderFile() {
    this.selectFolder.isVisible = false;
    if (this.parentId === 'root') {
      this.formInfo['folderId'] = 'root';
      this.formInfo['folderName'] = 'root';
      return;
    }
    this.formInfo['folderId'] = this.parentId;
    for (const folder of  this.folderList) {
      if (this.parentId === folder.id) {
        this.formInfo['folderName'] = folder['name'];
      }
    }
  }

  /**
   * 提交
   */
  public createOk(formInfo) {
    this.appService.setLoading(true);
    const req = {
      name: formInfo.name,
      url: formInfo.url,
      folderId: formInfo.folderId,
      folderName: formInfo.folderName
    };
    if (CommonTool.notNull(formInfo.id)) {
      this.fileManagementService.updateUserSafetyChain(formInfo.id, req).subscribe(res => {
        this.formInfo = {
          id: '',
          name: '',
          url: '',
          folderId: '',
          folderName: ''
        };
        this.tableFindModel.getData(null, null);
        this.isEditVisible = false;
        this.message.success('更新成功！');
      });
    } else {
      this.fileManagementService.createUserSafetyChain(req).subscribe(res => {
        this.formInfo = {
          id: '',
          name: '',
          url: '',
          folderId: '',
          folderName: ''
        };
        this.isEditVisible = false;
        this.tableFindModel.getData(null, null);
        this.message.success('创建成功！');
      });
    }
  }

  /**
   * 删除
   * 参数 id 数据主键
   */
  public delete(id) {
    this.modalService.confirm({
      nzTitle: '确实要删除吗?',
      nzContent: '<b style="color: red;">删除后将无法恢复！</b>',
      nzOkText: '确定',
      nzOnOk: () => {
        this.appService.setLoading(true);
        this.fileManagementService.deleteUserSafetyChain(id).subscribe(res => {
          this.tableFindModel.getData(null, null);
          this.message.success('删除成功！');
        });
      },
      nzCancelText: '取消'
    });
  }
}
